package com.vpen.server.http.handler;

import cn.hutool.core.util.ByteUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.sql.Time;
import java.util.concurrent.TimeUnit;

/**
 * 描述
 *
 * @author 韦鹏
 * @date 2024/4/5 22:46
 */
@Slf4j
public class HttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) {
// 处理HTTP请求
        if (!request.decoderResult().isSuccess()) {
            sendError(ctx, HttpResponseStatus.BAD_REQUEST);
            return;
        }


        ByteBuf buf = ByteBufAllocator.DEFAULT.heapBuffer();
        buf.writeBytes("HTTP/1.1 200 OK\r\n".getBytes(StandardCharsets.ISO_8859_1));
        buf.writeBytes("Content-Type: application/octet-stream\r\n".getBytes(StandardCharsets.ISO_8859_1));
        buf.writeBytes("\r\n".getBytes(StandardCharsets.ISO_8859_1));
        ctx.writeAndFlush(buf.array());

        // ... 这里添加你的业务逻辑代码，例如路由分发、处理GET/POST请求等

//        // 构建HTTP响应
        DefaultFullHttpResponse response = new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK,
                Unpooled.copiedBuffer("Hello, World!", CharsetUtil.UTF_8));

        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
        response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());

        // 写出响应并关闭连接（或保持连接）
//        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        ctx.writeAndFlush(response);
        try {
            DefaultFullHttpResponse response2 = new DefaultFullHttpResponse(
                    HttpVersion.HTTP_1_1,
                    HttpResponseStatus.OK,
                    Unpooled.copiedBuffer("Hello, World000000000!", CharsetUtil.UTF_8));

            response2.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
            response2.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, response2.content().readableBytes());
            Thread.sleep(50);
            ctx.writeAndFlush(response2);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
        FullHttpResponse response = new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer("Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8));
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");

        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }
}
